import { reqGetCode, reqUserRegister, reqUserLogin, reqUserInfo, reqLogout } from '@/api/index'
// 存储token
import { setToken, getToken, removeToken } from '@/utils/token'

// 登陆与注册模块的小仓库
const state = {
    // 服务器返回对象 初始值为对象 返回数组 初始值为数组
    code: '',
    token: '',
    userInfo: getToken()
}
const mutations = {
    GETCODE(state, code) {
        state.code = code
    },
    USERLOGIN(state, token) {
        state.token = token
    },
    GETUSERINFO(state, userInfo) {
        state.userInfo = userInfo
    },
    CLEAR(state) {
        state.token = '',
            state.userInfo = {},
            removeToken()
    }
}
const actions = {
    // 获取验证码
    async getCode({ commit }, phone) {
        let result = await reqGetCode(phone)
            // console.log(result)
        if (result.code == 200) {
            commit('GETCODE', result.data)
            return 'OK'
        } else {
            return Promise.reject(new Error('code failed'))
        }
    },
    // 用户注册
    async userRegister({ commit }, user) {
        let result = await reqUserRegister(user)
            // console.log(result)
        if (result.code == 200) {
            return 'OK'
        } else {
            return Promise.reject(new Error('register failed'))
        }
    },
    // 登陆业务 校验token
    async userLogin({ commit }, data) {
        let result = await reqUserLogin(data)
            // console.log(result)
        if (result.code == 200) {
            // 服务器下发token 唯一标识
            // 存储标识 向服务器发请求带上token请求数据  存储在Vuex 非持久化
            commit('USERLOGIN', result.data.token)
                // 持久化存储token
                // localStorage.setItem('TOKEN', result.data.token)
            setToken(result.data.token)
            return 'OK'
        } else {
            return Promise.reject(new Error('login failed'))
        }
    },
    // 获取用户信息
    async getUserInfo({ commit }) {
        let result = await reqUserInfo()
            // console.log(result)
        if (result.code == 200) {
            commit('GETUSERINFO', result.data)
            return 'OK'
        } else {
            return Promise.reject(new Error('getUserInfo failed'))
        }
    },
    // 退出登陆
    async userLogout({ commit }) {
        // 向服务器发请求清除token
        let result = await reqLogout()
            // action不操作state
        if (result.code == 200) {
            commit('CLEAR')
            return 'OK'
        } else {
            return Promise.reject(new Error('logout failed'))
        }
    }
}
const getters = {}

export default {
    state,
    mutations,
    actions,
    getters
}